package cn.richard.demo.tax.config;

import java.io.IOException;

import org.kie.api.KieBase;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
public class DroolsConfig {
	//指定规则文件存放的目录
    private static final String RULES_PATH = "rules/";
    
    @Bean
    @ConditionalOnMissingBean
    public KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = KieUtil.kieServices.newKieFileSystem();
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] files = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "*.drl");
        String path = null;
        for (Resource file : files) {
            path = RULES_PATH + file.getFilename();
            kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
        }
        return kieFileSystem;
    }
    
    @Bean
    @ConditionalOnMissingBean
    public KieContainer kieContainer(KieFileSystem kieFileSystem){
        KieRepository kieRepository = KieUtil.kieServices.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kieBuilder = KieUtil.kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        KieContainer kieContainer = KieUtil.kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
        KieUtil.setKieContainer(kieContainer);
		return kieContainer;
    }
    
    /**
     * KieBase 还有用吗..<br>
     * kieContainer.newKieSession() vs kieBase.newKieSession()<br>
     * Q：KieContainer、KieSession、KieHelper、KieBase... 之间的关系
     * @return
     * @throws IOException
     */
    @Bean
    @ConditionalOnMissingBean
    public KieBase kieBase(KieContainer kieContainer) {
        KieBase kieBase = kieContainer.getKieBase();
		return kieBase;
    }
    
    @Bean
    @ConditionalOnMissingBean
    public KModuleBeanFactoryPostProcessor kiePostProcessor() {
        return new KModuleBeanFactoryPostProcessor();
    }
}
